<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/17
 * Time: 11:01
 */

namespace App\Http\Controllers;


use App\Models\Activity;
use App\Models\Address;
use App\Models\Join;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AddressController extends Controller
{
    /**
     * 获取个人地址信息 get
     * @param Request $request
     * @param userid required
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function info(){
        $user_id = auth()->guard('api')->id();
        $info = Address::find(['user_id'=>$user_id]);
        if($info){
            return $this->returnJson(0,'',$info);
        }
        return $this->returnJson(1,'error');

    }

    /**
     * 获取参与活动中奖用户信息
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function winUserInfo(){
        $user_id = auth()->guard('api')->id();
        $activity_id = (int)request('activity_id','');
        $activityModel = Activity::find($activity_id);

        if(!$activityModel){
            return $this->returnJson(1,'error');
        }

        if($activityModel->user_id == $user_id){
            $joinUser = Join::where('activity_id',$activity_id)->whereBetween('status', [1, 3])->with(['user'])
                ->orderBy('status', 'asc')
                ->paginate(10);;
            return $this->returnJson(0,'',$joinUser);
        }
        return $this->returnJson(1,'error');
    }
    /**
     * 更新个人地址信息 post
     * @param Request $request
     * @param userid required
     * @param mobile required
     * @param address required
     * @param code
     * @param name
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function update(Request $request){
        $data = $request->all();
        $user_id = auth()->guard('api')->id();
        // 通过属性获取地址, 如果不存在则创建...
        $data['user_id'] = $user_id;
        try{
            $find = Address::where(['user_id' =>$user_id])->first();
            if(!$find){
                Address::create($data);
            }else{
                $find->update($data);
            };
        }catch (\Exception $exception){
            Log::error($exception);
            return $this->returnJson(1,'系统繁忙,地址修改失败');
        }
        return $this->returnJson(0);
    }

}